package org.example.translate_braille.utils;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.region.Region;

import java.io.File;
import java.util.Random;

public class TencentCosUtil {
    // 存储桶名称
    private static final String bucketName = "aaa-1309977808";
    //secretId 秘钥id
    private static final String SecretId = "AKIDuc4GAn9F3brqYz92ez3qNdcKlumNhkW1";
    //SecretKey 秘钥
    private static final String SecretKey = "FDuJSKvFJ7eusZz81cwzlFSO2PVQ4RaT";
    // 腾讯云 自定义文件夹名称
    private static final String prefix = "/upload_picture/";
    // 访问域名
    public static final String URL = "https://aaa-1309977808.cos.ap-guangzhou.myqcloud.com";
    // 创建COS 凭证
    private static final COSCredentials credentials = new BasicCOSCredentials(SecretId,SecretKey);
    // 配置 COS 区域 就购买时选择的区域
    private static final ClientConfig clientConfig = new ClientConfig(new Region("ap-guangzhou"));

    public static String uploadfile(File file,String fileName){
        // 创建 COS 客户端连接
        COSClient cosClient = new COSClient(credentials,clientConfig);
        try {
            // 将 文件上传至 COS
            Random random = new Random();
            fileName=random.nextInt(10000)+fileName;
            PutObjectRequest objectRequest = new PutObjectRequest(bucketName,prefix+fileName,file);
            cosClient.putObject(objectRequest);
            System.out.println("insert into cos success!");
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            cosClient.shutdown();
        }

        return URL+prefix+fileName;
    }

    public static void delFile(String filename){
        new Thread(() -> {
            // 创建 COS 客户端连接
            COSClient cosClient = new COSClient(credentials,clientConfig);
            try{
                String key=prefix+filename;
                cosClient.deleteObject(bucketName, key);
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                cosClient.shutdown();
            }
        }).start();
    }

}